package cn.edu.gzgs.controller;

import cn.edu.gzgs.dto.EmailListDTO;
import cn.edu.gzgs.service.EmailMsgService;
import cn.edu.gzgs.service.WebSocketMessageService;
import cn.edu.gzgs.vo.ApiResponse;
import cn.edu.gzgs.websocket.WebSocketServer;
import cn.edu.gzgs.entity.User;
import cn.edu.gzgs.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 邮件API控制器
 */
@Tag(name = "邮件接口", description = "邮件管理相关接口")
@RestController
@RequestMapping("/api/email")
@Slf4j
public class EmailController {

    @Autowired
    private EmailMsgService emailMsgService;
    
    @Autowired
    private WebSocketMessageService webSocketMessageService;
    
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取用户邮件列表
     */
    @Operation(summary = "获取邮件列表", description = "获取当前用户的所有邮件列表")
    @GetMapping("/list/{id}")
    public ResponseEntity<ApiResponse<List<EmailListDTO>>> getEmailList(
            @Parameter(description = "用户ID") @PathVariable String id) {
        
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUserNo = authentication.getName(); // JWT中存储的是工号
            
            // 根据工号查询当前用户信息
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_no", currentUserNo);
            User currentUser = userMapper.selectOne(queryWrapper);
            
            if (currentUser == null) {
                log.warn("认证用户工号 {} 在数据库中未找到", currentUserNo);
                return ResponseEntity.status(401)
                        .body(ApiResponse.error(401, "用户认证信息异常"));
            }
            
            // 权限验证：只能查看自己的邮件
            if (!currentUser.getId().toString().equals(id)) {
                log.warn("用户 {} (ID:{}) 尝试访问用户 {} 的邮件列表", currentUserNo, currentUser.getId(), id);
                return ResponseEntity.status(401)
                        .body(ApiResponse.error(401, "无权限访问该用户的邮件"));
            }

            List<EmailListDTO> emailList = emailMsgService.getEmailList(id);
            log.info("用户 {} 获取邮件列表，共 {} 条", id, emailList.size());
            
            return ResponseEntity.ok(ApiResponse.success(emailList));
            
        } catch (Exception e) {
            log.error("获取邮件列表失败: 用户ID = {}", id, e);
            return ResponseEntity.status(500)
                    .body(ApiResponse.error(500, "获取邮件列表失败"));
        }
    }

    /**
     * 批量标记邮件为已读
     */
    @Operation(summary = "标记邮件已读", description = "批量标记邮件为已读状态")
    @GetMapping("/readStatus")
    public ResponseEntity<ApiResponse<String>> markAsRead(
            @Parameter(description = "邮件ID列表，用逗号分隔") @RequestParam String ids) {
        
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUserNo = authentication.getName(); // JWT中存储的是工号
            
            // 根据工号查询当前用户信息
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_no", currentUserNo);
            User currentUser = userMapper.selectOne(queryWrapper);
            
            if (currentUser == null) {
                log.warn("认证用户工号 {} 在数据库中未找到", currentUserNo);
                return ResponseEntity.status(401)
                        .body(ApiResponse.error(401, "用户认证信息异常"));
            }

            // 解析邮件ID列表
            List<Long> emailIds = parseIds(ids);
            if (emailIds.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(400, "邮件ID参数无效"));
            }

            int updatedCount = emailMsgService.batchMarkAsRead(emailIds, currentUser.getId().toString());
            log.info("用户 {} 标记 {} 条邮件为已读", currentUserNo, updatedCount);
            
            return ResponseEntity.ok(ApiResponse.success("成功标记 " + updatedCount + " 条邮件为已读"));
            
        } catch (Exception e) {
            log.error("标记邮件已读失败: ids = {}", ids, e);
            return ResponseEntity.status(500)
                    .body(ApiResponse.error(500, "标记邮件已读失败"));
        }
    }

    /**
     * 批量删除邮件
     */
    @Operation(summary = "删除邮件", description = "批量删除邮件")
    @DeleteMapping
    public ResponseEntity<ApiResponse<String>> deleteEmails(
            @Parameter(description = "邮件ID列表，用逗号分隔") @RequestParam String ids) {
        
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUserNo = authentication.getName(); // JWT中存储的是工号
            
            // 根据工号查询当前用户信息
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_no", currentUserNo);
            User currentUser = userMapper.selectOne(queryWrapper);
            
            if (currentUser == null) {
                log.warn("认证用户工号 {} 在数据库中未找到", currentUserNo);
                return ResponseEntity.status(401)
                        .body(ApiResponse.error(401, "用户认证信息异常"));
            }

            // 解析邮件ID列表
            List<Long> emailIds = parseIds(ids);
            if (emailIds.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(400, "邮件ID参数无效"));
            }

            int deletedCount = emailMsgService.batchDelete(emailIds, currentUser.getId().toString());
            log.info("用户 {} 删除 {} 条邮件", currentUserNo, deletedCount);
            
            return ResponseEntity.ok(ApiResponse.success("成功删除 " + deletedCount + " 条邮件"));
            
        } catch (Exception e) {
            log.error("删除邮件失败: ids = {}", ids, e);
            return ResponseEntity.status(500)
                    .body(ApiResponse.error(500, "删除邮件失败"));
        }
    }

    /**
     * 测试WebSocket消息推送
     */
    @Operation(summary = "测试WebSocket", description = "测试WebSocket消息推送功能")
    @GetMapping("/test-websocket/{userId}")
    public ResponseEntity<ApiResponse<String>> testWebSocket(
            @Parameter(description = "用户ID") @PathVariable String userId) {
        
        try {
            // 发送项目通过通知
            webSocketMessageService.sendProjectPassNotification(userId, "测试项目", "1001", "测试审核老师");
            
            // 发送项目拒绝通知
            webSocketMessageService.sendProjectRepulseNotification(userId, "测试项目", "测试审核意见", "1001", "测试审核老师");
            
            log.info("已向用户 {} 发送审核通知测试消息", userId);
            
            return ResponseEntity.ok(ApiResponse.success("审核通知测试消息已发送给用户: " + userId));
            
        } catch (Exception e) {
            log.error("审核通知测试失败: 用户ID = {}", userId, e);
            return ResponseEntity.status(500)
                    .body(ApiResponse.error(500, "审核通知测试失败"));
        }
    }

    /**
     * 解析ID字符串为Long列表
     */
    private List<Long> parseIds(String ids) {
        try {
            return Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            log.warn("解析ID字符串失败: {}", ids, e);
            return List.of();
        }
    }
}